//
//  ViewController.m
//  综合练习3验证码
//
//  Created by 小白 on 16/3/1.
//  Copyright © 2016年 小白. All rights reserved.
//

#import "ViewController.h"
#import "GetPicture.h"
int count=0;

@interface ViewController ()<UIAlertViewDelegate>
//设置plist的数组
@property (nonatomic,copy) NSArray *arr;
@property (nonatomic,copy) NSMutableArray *mArrchinese;
@property (nonatomic,copy) NSMutableArray *mArrimages;
@property (nonatomic,copy) NSString *img;
@property (nonatomic,weak) UILabel *labelNote;
@property (nonatomic,weak) UIView *mainView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //取数据
    NSString *path = [[NSBundle mainBundle] pathForResource:@"codes" ofType:@"plist"];
    NSArray *allArr = [NSArray arrayWithContentsOfFile:path];
    NSMutableArray *arrChinese = [NSMutableArray array];
    NSMutableArray *arrImages = [NSMutableArray array];
    //不能直接用属性 不然得不到数据
    //    self.mArrchinese = [NSMutableArray array];
    //    self.mArrimages = [NSMutableArray array];
    //遍历总数组将其Dictionary元素组的对应的key 的值重新组成数组
    for(NSDictionary *e in allArr){
        [arrChinese addObject:e[@"chinese"]];
    }
    self.mArrchinese = arrChinese;
    //获取图片数组
    for (int i = 0; i<5; i++) {
        //遍历对应数组元素
        for(NSString *element in allArr[i][@"images"])
        {
            [arrImages addObject:element];
        }
    }
    //属性
    self.mArrimages = arrImages;
    
    //创建label
    UILabel *labelExplain = [[UILabel alloc]initWithFrame:CGRectMake(0, 80, 150, 20)];
    labelExplain.text = @"点击下图所有的";
    labelExplain.textAlignment = UITextAlignmentLeft;
    labelExplain.font = [UIFont systemFontOfSize:20];
    [self.view addSubview:labelExplain];
    //创建指示label
    UILabel *labelType = [[UILabel alloc]initWithFrame:CGRectMake(150, 80, 50, 20)];
    labelType.text = nil;
    labelType.textAlignment = UITextAlignmentLeft;
    labelType.font = [UIFont systemFontOfSize:20];
    self.labelNote = labelType;
    [self.view addSubview:labelType];
    /*imageview 创建iamgeview 
     将button的图片放在imageview里面
     因为button的image会覆盖title
     设置button title
    */
    UIImageView *btnV = [[UIImageView alloc]initWithFrame:CGRectMake(0,0,40,30)];
    btnV.image = [UIImage imageNamed:@"refresh"];
    //创建刷新按钮
    UIButton *btnRefresh = [[UIButton alloc]initWithFrame:CGRectMake(240, 80, 80, 30)];
    [btnRefresh setTitle:@"刷新" forState:UIControlStateNormal];
    [btnRefresh setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [btnRefresh setTitleEdgeInsets:UIEdgeInsetsMake(0, 40, 0, 0)];
    [btnRefresh addTarget:self action:@selector(change) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnRefresh];
    [btnRefresh addSubview:btnV];
    
    //创建mainView 用于存放验证图片
    UIView *viewVision = [[UIView alloc]initWithFrame:CGRectMake(0, 150, 320, 180)];
    self.mainView = viewVision;
    [self.view addSubview:viewVision];
   
    //创建登陆按钮
    UIButton *loginBtn = [[UIButton alloc]initWithFrame:CGRectMake(80, 350, 160, 40)];
    [loginBtn setTitle:@"登陆" forState:UIControlStateNormal];
    [loginBtn setBackgroundColor:[UIColor orangeColor]];
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginBtn addTarget:self action:@selector(judge) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loginBtn];
    //创建验证图片 并刷新
    [self refresh];
    [self change];
}

//封装简易button
-(void)addButtonWithaction:(SEL)action  frame:(CGRect)frame image:(NSString *)image inttitle:(int)title
{
    UIButton *btn = [[UIButton alloc]initWithFrame:frame];
    [btn setBackgroundImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
    [btn setTitle:[NSString stringWithFormat:@"%d",title] forState:UIControlStateNormal];
    [btn addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    [btn setTitle:nil forState:UIControlStateNormal];
    //封装添加button在mainview
    [self.mainView addSubview:btn];
}

// 创建button组 存放images
-(void)refresh
{
    //创建可变数组用于存储count值
    NSMutableArray *mArr = [NSMutableArray array];
    //创建button组
    for (int i = 0; i<8; i++) {
        count = arc4random()%30;
        NSString *img = [self.mArrimages objectAtIndex:count];
        if (i<4) {
            [self addButtonWithaction:@selector(click:) frame:CGRectMake(i*80, 0, 80, 90) image:img inttitle:count];
        }
        else
        {
            [self addButtonWithaction:@selector(click:) frame:CGRectMake((i-4)*80, 90, 80, 90) image:img inttitle:count];
        }
        [mArr addObject:[NSString stringWithFormat:@"%d",count/6]];
    }
    //随机mArr中获得的创建images时候的数值 作为mArrchinese的index进行输出提示文字
    int num = [[mArr objectAtIndex:arc4random()%8] intValue];
    self.labelNote.text = [self.mArrchinese objectAtIndex:num];
    self.labelNote.textColor = [UIColor redColor];
}


//刷新图片功能
-(void)change
{
    /*判断并使其输出的图片不重复
     步骤:1.创建mutablearray（用于添加已出现的数值） 和 array （用于遍历mutablearray中的元素）
     注:可变数组是不可以枚举遍历的 所以要用数组代替
         2.创建while死循环 直到满足条件才会跳出循环
         3.设置检测参数 ，符合要求则赋值 并跳出
     */
    NSMutableArray *mArr = [NSMutableArray array];
    NSMutableArray *mrepeat = [NSMutableArray array];
    NSArray *repeat = [NSArray array];
    int number = 0;
    for(id element in self.mainView.subviews)
    {
        
        BOOL a = YES;
        while (a) {
            
            int after = 0;
            number = arc4random()%30;
            
            //            [mrepeat addObject:[NSString stringWithFormat:@"%d",count]];
            
            if (mrepeat.count == 0) {
                
                [mrepeat addObject:[NSString stringWithFormat:@"%d",number]];
                repeat = mrepeat;
                a = NO;
            }
            else{
                
                for (NSString *element  in repeat)
                {
                    if ([element isEqualToString:[NSString stringWithFormat:@"%d",number]]) {
                        after++;
                    }
                    
                }
                if (after == 0) {
                    [mrepeat addObject:[NSString stringWithFormat:@"%d",number]];
                    repeat = mrepeat;
                    a = NO;
                }
                
            }
        }
        //  从images中取值并设置
        NSString *img = [self.mArrimages objectAtIndex:number];
        if ([element isKindOfClass:[UIButton class]]) {
            UIButton *btn = element;
            [btn setBackgroundImage:[UIImage imageNamed:img] forState:UIControlStateNormal];
            [btn setTitle:[NSString stringWithFormat:@"%d",number] forState:UIControlStateNormal];
            [btn setTitleEdgeInsets:UIEdgeInsetsMake(80, 70, 0, 0)];
            //使所有button的初始状态为未选中状态
            btn.selected = NO;
        }
        [mArr addObject:[NSString stringWithFormat:@"%d",number/6]];
    }
    int num = [[mArr objectAtIndex:arc4random()%8] intValue];
    self.labelNote.text = [self.mArrchinese objectAtIndex:num];
    self.labelNote.textColor = [UIColor redColor];
}

//验证图片的点击事件 主要是selected 与 nomal 之间的转换
-(void)click:(UIButton *)sender
{
    UIButton *btn = sender;
    if (btn.selected)
    {
        btn.selected = NO;
    }
    else
    {
        btn.selected = YES;
        //设置在selected状态下的右下角的角标
        [btn setImage:[UIImage imageNamed:@"con"] forState:UIControlStateSelected];
        [btn setImageEdgeInsets:UIEdgeInsetsMake(70, 60, 0, 0)];
    }
}
//登陆判断
-(void)judge
{
    //计数器
    int countt = 0;
    int countt2 = 0;
    int countt3 = 0;
    //判断chinese的index
    int n=0;
    if ([self.labelNote.text isEqualToString:@"水果"]) {
        n = 0;
    }
    else if ([self.labelNote.text isEqualToString:@"台灯"])
    {
        n = 1;
    }
    else if ([self.labelNote.text isEqualToString:@"动物"])
    {
        n = 2;
    }
    else if ([self.labelNote.text isEqualToString:@"衣服"])
    {
        n = 3;
    }
    else if ([self.labelNote.text isEqualToString:@"鞋子"])
    {
        n = 4;
    }
    //遍历mainview的子视图
    for(id element in self.mainView.subviews)
    {
        //找到mainview中的所有button
        if ([element isKindOfClass:[UIButton class]]) {
            UIButton *btn = element;
            //这里把btn的title作为传值的媒介 title 为image在marrimages中的index
            int value = [btn.titleLabel.text intValue];
            //只有当被选数与指定的数相等时候才成功
            if (btn.selected)
            {
                countt++;
                
                if (value/6 == n ) {
                    countt2++;
                }
            }
            if (value/6 == n)
            {
                countt++;
                
                if (btn.selected) {
                    countt2++;
                }
            }
        }
    }
    //弹出提示框
    if (countt == countt2 && countt > 0 ) {

        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"登陆成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"登陆失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
